package com.job2e.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.jbauble.mvc.Filter;
import com.google.code.jbauble.mvc.support.UrlTool;

public class AuthorizationFilter implements Filter {
	private UrlTool urlTools = new UrlTool();
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public boolean doFilter(HttpServletRequest request,
			HttpServletResponse response) {
        String url = request.getRequestURI();
        if (url.indexOf("/jobs") > -1 && !isExcludePage(url) && request.getSession().getAttribute("user") == null) {
        	try {
				response.sendRedirect(urlTools.get("jobs", "login"));
			} catch (IOException e) {
				log.error("jobs/login", e);
			}
        	return false;
        }
        if (url.indexOf("/hr") > -1 && !isExcludePage(url) && request.getSession().getAttribute("hr") == null) {
        	try {
				response.sendRedirect(urlTools.get("hr", "login"));
			} catch (IOException e) {
				log.error("hr/login", e);
			}
        	return false;
        }
		return true;
	}
	
	private final String[] excludePages = new String[] {"login", "logout", "register"};
	
	private boolean isExcludePage(String url) {
		for (String p : excludePages) {
			if (url.indexOf(p) > -1)
				return true;
		}
		return false;
	}

}
